package com.itmumu.miniwechat.user.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itmumu.miniwechat.user.domain.po.User;
import com.itmumu.miniwechat.common.constants.RedisKey;
import com.itmumu.miniwechat.common.utils.RedisUtils;
import com.itmumu.miniwechat.user.handler.TextBuilder;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class WxMsgService {

    @Autowired
    @Lazy
    private UserService userService;


    /**
     * 用户的openId和前端登录场景code的映射关系
     */
    private static final String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    @Value("${wx.mp.callback}")
    private String callback;


    public WxMpXmlOutMessage scan(WxMpService wxMpService, WxMpXmlMessage wxMpXmlMessage) {

        String ticket = wxMpXmlMessage.getTicket();
        String openid = wxMpXmlMessage.getFromUser();
        log.info("用户的openid是：{}", openid);
        Integer loginCode = Integer.parseInt(getEventKey(wxMpXmlMessage));

        // 做ticket的解锁
        String hasTicket = RedisUtils.get(RedisKey.getKey(RedisKey.LOGIN_TICKET + ticket), String.class);

        String tipMessage = "";
        if (Objects.nonNull(hasTicket) && StringUtils.isNotEmpty(hasTicket)) {
            // 查询用户是否存在，存在则直接发放token
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getOpenid, openid);
            User user = userService.getOne(wrapper);
            if (!Objects.nonNull(user)) { // 为空，说明用户不存在，执行注册
                user = new User().builder().openid(openid).build();
                try {
                    WxMpUser wxMpUser = wxMpService.getUserService().userInfo(user.getOpenid());
                    System.out.println(wxMpUser.toString());
                    Boolean subscribe = wxMpUser.getSubscribe();
                    Long subscribeTime = wxMpUser.getSubscribeTime();

                    user.setIsFollow(subscribe ? 1 : 0);
                    user.setFollowtime(subscribeTime);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                userService.register(user);
            }

            // 删除原有的ticket信息后，前端轮询接口会收到token
            RedisUtils.del(RedisKey.getKey(RedisKey.LOGIN_TICKET + ticket));

            // 存在当前扫码的ticket，说明用户已经扫了码
            tipMessage = "登录成功";
        } else {
            tipMessage = "验证失败，请重新获取二维码";
        }

        WxMpXmlOutMessage.TEXT().build();
        return new TextBuilder().build(tipMessage, wxMpXmlMessage, wxMpService);
    }

    private String getEventKey(WxMpXmlMessage wxMpXmlMessage) {
        //扫码关注的渠道事件有前缀，需要去除
        return wxMpXmlMessage.getEventKey().replace("qrscene_", "");
    }


    /**
     * 用户公众号输入事件
     * @param wxMessage
     * @return
     */
    public WxMpXmlOutMessage message(WxMpService wxMpService, WxMpXmlMessage wxMessage) {
        String openid = wxMessage.getFromUser();
        log.info("用户的openid是：{}", openid);

        // 获取用户输入内容
        String content = wxMessage.getContent();

        // 从redis中获取信息
        String cacheEventCode = RedisUtils.get(RedisKey.getKey(RedisKey.LOGIN_EVENT_CODE + content), String.class);

        //组装回复消息
        String respContent = "";

        // redis中存在，说明是该用户输入，执行登录/注册
        if (Objects.nonNull(cacheEventCode)) {
            // 处理登录逻辑
            respContent = "登录成功";
        } else {
            respContent = "登录失败";
        }

        return new TextBuilder().build(respContent, wxMessage, wxMpService);
    }

    /**
     * 用户授权
     *
     * @param userInfo
     */
    public void authorize(WxOAuth2UserInfo userInfo) {
        //找到对应的code
        log.info("用户授权。。。。");
    }


}
